package io.huaguoguo.juc;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.format.FastDateFormat;
import cn.hutool.core.util.RandomUtil;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * @Title:
 * @Description: 超时定时自动消息demo
 * @author: huaguoguo
 * @Date： 2021/6/8 18:42
 */
@Slf4j
public class DelayOrderDemo {

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    static
    class Order implements Delayed {
        private String orderNo;
        private Date orderDate;

        @Override
        public long getDelay(TimeUnit unit) {
            return unit.convert(orderDate.getTime() - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
        }

        @Override
        public int compareTo(Delayed o) {
            return (int) (this.getDelay(TimeUnit.MILLISECONDS) - o.getDelay(TimeUnit.MILLISECONDS));
        }
    }

    public static void main(String[] args) throws InterruptedException {
        DelayQueue<Order> orders = new DelayQueue<>();
        Date baseDate = new Date();
        for (int i = 0; i < 10; i++) {
            String orderNo = UUID.randomUUID().toString();
            DateTime orderDate = RandomUtil.randomDate(baseDate, DateField.MILLISECOND, 1000, 5000);
            orders.add(new Order(orderNo, orderDate));
            log.info("订单等待取消：" + orderNo + " - " + DateUtil.format(orderDate, DatePattern.NORM_DATETIME_MS_PATTERN));
        }

        while (orders.size() > 0) {
            Order order = orders.take();
            log.info("订单取消：" + order.orderNo + " - " + DateUtil.format(order.orderDate, DatePattern.NORM_DATETIME_MS_PATTERN));
        }
    }
}
